package com.edu.hre.struts.action.admin;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.MessageResources;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreOrganizationGenInfo;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.OrgGenInfoForm;

public class OrgGenInfoAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(OrgGenInfoAction.class);
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "genInfo";
 
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());

		OrgGenInfoForm beanForm = (OrgGenInfoForm) form; 

		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		beanForm.setCanUpdate(userRoleScreen.isCanUpdate());

		if(request.getParameter("btnUpdate") != null){
			ActionErrors errors = validateForm(request, beanForm);
			if (errors != null && !errors.isEmpty()) {
				saveErrors(request, errors);
				beanForm.setMessage(StringConstants.BLANK);
				return mapping.findForward(ACTION_NAME);
			}
			
			HreOrganizationGenInfo tmp = null;
			int id = 0;

			if(!StringUtils.isBlank(beanForm.getId())){
				id = Integer.parseInt(beanForm.getId());
			}

			tmp = baseService.getFirstPojo("id", Compare.EQUAL, id, null, null, 0, HreOrganizationGenInfo.class);
			if (tmp == null) {
				tmp = new HreOrganizationGenInfo();
				tmp.setDateCreated(new Date());
			}
			
			if (!"".equalsIgnoreCase(CommonUtils.normalizeString(beanForm.getPhone())) && !CommonUtils.verifyPhoneNumber(CommonUtils.normalizeString(beanForm.getPhone()))) {
				invalidError(request, "phone.invalid", "label.organization.phone");
				beanForm.setMessage(StringConstants.BLANK);
				return mapping.findForward(ACTION_NAME);
			}
			
			if (!"".equalsIgnoreCase(CommonUtils.normalizeString(beanForm.getFax())) && !CommonUtils.verifyFaxNumber(CommonUtils.normalizeString(beanForm.getFax()))) {
				invalidError(request, "fax.invalid", "label.organization.fax");
				beanForm.setMessage(StringConstants.BLANK);
				return mapping.findForward(ACTION_NAME);
			}
			
			if (!"".equalsIgnoreCase(CommonUtils.normalizeString(beanForm.getEmail())) && !CommonUtils.verifyEmail(CommonUtils.normalizeString(beanForm.getEmail()))) {
				invalidError(request, "email.invalid", "label.organization.email");
				beanForm.setMessage(StringConstants.BLANK);
				return mapping.findForward(ACTION_NAME);
			}

			tmp.setName(CommonUtils.normalizeString(beanForm.getName()));
			tmp.setTaxId(CommonUtils.normalizeString(beanForm.getTaxId()));
			tmp.setRegistrationNumber(CommonUtils.normalizeString(beanForm.getRegistrationNumber()));
			tmp.setPhone(CommonUtils.normalizeString(beanForm.getPhone()));
			tmp.setFax(CommonUtils.normalizeString(beanForm.getFax()));
			tmp.setEmail(CommonUtils.normalizeString(beanForm.getEmail()));
			tmp.setProvince(CommonUtils.normalizeString(beanForm.getProvince()));
			tmp.setDistrict(CommonUtils.normalizeString(beanForm.getDistrict()));
			tmp.setStreet(CommonUtils.normalizeString(beanForm.getStreet()));
			tmp.setNote(CommonUtils.normalizeString(beanForm.getNote()));
			tmp.setDateModified(new Date());

			if(baseService.saveOrUpdate(tmp)){
				passiveDynaCache.removeCachedItem(RequestUtils.Attribute.LIST_SUB_UNITS_STRUCTURE);
				beanForm.setMessage("Organization information has been updated successfully!");
			} else {
				invalidError(request, "save.failure", "label.organization");
				beanForm.setMessage(StringConstants.BLANK);
			}

			return mapping.findForward(ACTION_NAME);
		}

		HreOrganizationGenInfo info =  baseService.getFirstPojo(null, -1, null, null, null, 0, HreOrganizationGenInfo.class);
		if (info != null) {

			beanForm.setId(info.getId() + StringConstants.BLANK);
			beanForm.setName(CommonUtils.normalizeString(info.getName()));
			beanForm.setTaxId(CommonUtils.normalizeString(info.getTaxId()));
			beanForm.setRegistrationNumber(CommonUtils.normalizeString(info.getRegistrationNumber()));
			beanForm.setPhone(CommonUtils.normalizeString(info.getPhone()));
			beanForm.setFax(CommonUtils.normalizeString(info.getFax()));
			beanForm.setEmail(CommonUtils.normalizeString(info.getEmail()));
			beanForm.setProvince(CommonUtils.normalizeString(info.getProvince()));
			beanForm.setDistrict(CommonUtils.normalizeString(info.getDistrict()));
			beanForm.setStreet(CommonUtils.normalizeString(info.getStreet()));
			beanForm.setNote(CommonUtils.normalizeString(info.getNote()));

			int numOfEmp = baseService.countByColumns(new String[]{"isDeleted"}, new int[]{Compare.EQUAL}, new Boolean[]{false}, "empNumber", HreEmployee.class);
			beanForm.setNumOfEmp(numOfEmp + StringConstants.BLANK);

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
		}

		initFormBean(beanForm);
		return mapping.findForward(ACTION_NAME);
	}

	private void initFormBean(OrgGenInfoForm beanForm) {

		beanForm.setAllDistricts(ComboBoxInit.getAllDistricts(true));
		beanForm.setAllProvinces(ComboBoxInit.getAllProvinces(true));
	}
	
	private ActionErrors validateForm(HttpServletRequest request, OrgGenInfoForm beanForm) {
		ActionErrors errors = new ActionErrors();
		try { 
			MessageResources messages = getResources(request);
			if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getName()))){  
				errors.add("error", new ActionMessage("errors.required", messages.getMessage(getLocale(request), "label.organization.name")));
			}  
		} catch (Exception e) {
			logger.error("OrgGenInfoAction - validateLogin() = " + e);
		}
		return errors;
	}
	
	private ActionErrors invalidError (HttpServletRequest request, String quoteKeyWord, String keyWord) {
		ActionErrors errors = new ActionErrors();
		try { 
			MessageResources messages = getResources(request);
			errors.add("error", new ActionMessage(quoteKeyWord, messages.getMessage(getLocale(request), keyWord)));
			saveErrors(request, errors);
		} catch (Exception e) {
			logger.error("OrgGenInfoAction - validateLogin() = " + e);
		}
		return errors;
	}
}
